$(document).ready(function(){
        /*
         *$post()一个数据到服务端，取回首次需要展示的数据
         */
        treeAction.init(treeData);
        //treeAction.url = "http://www.baidu.com"
    });
var treeAction = {
    settings:{
        urlStruc: "../js/data2.js",//点击节点服务端接收的url
        urlNode:"../js/data3.js",
        appendNode:"",
        userId: 3
    },
    init:function(treeData){
        var settings = treeAction.settings;
        var url = settings.urlStruc;
        var currId = settings.userId;
        var appendNode = settings.appendNode;
        $(".J-forTree").removeAttr("disabled");
        $(".J-forTree").click(function(){
                if($("body").find(".treeCont").length == 0){
                    /*
                     *$post()一个数据到服务端，取回首次需要展示的数据
                     */
                    $.post(url,{userId:currId},function(data){
                            var data = eval('(' + data + ')');
                            if(data.success){
                                var treeData = data.treeData;
                                treeAction.createFirstLevel(treeData);
                                treeAction.bind();
                            }else if(data.error){
                                var status = data.status;
                                treeAction.showErrorMsg(status);
                            }
                        });
                }else{
                    $(".treeCont").show();
                }
                $(this).attr("disabled","disabled");
            });
    },
    bind:function(){
        $(".J-treeClose").click(function(){
                $(".treeCont").hide();
                $(".J-forTree").removeAttr("disabled");
            });
        if( !$(".J-switch").parent().parent().siblings("ul.level")){
            $(".J-switch").removeClass("open").addClass("noBtn");
        }
        //整棵树的全选和反选
        $(".J-checkAll").click(function(){
                if ( true === $(this).attr("checked") ){
                    $(".J-check:checkbox").attr("checked",true);
                } else if ( false === $(this).attr("checked") ){
                    $(".J-check:checkbox").attr("checked",false);
                }
            });
        //节点的全选和反选
        $(".J-checkValue").click(function(){
                if(true === $(this).attr("checked")){
                    if($(this).siblings(".J-switch").hasClass("close")){
                        $(this).siblings(".J-switch").click();
                    }
                    //alert(2)
                    $(this).parent().parent().parent("li").find(".J-check").attr("checked",true);
                }else if(false === $(this).attr("checked")){
                    $(this).parent().parent().parent("li").find(".J-check").attr("checked",false);
                    var pid = $(this).attr("pid");
                    $("#"+pid).children().children().children(".J-check").click();
                }
            });
        $(".J-checkName").click(function(){
                if(false == $(this).attr("checked")){
                    var p = $(this).parent().parent().siblings(".lft").children(".J-check");
                    if (p.attr("checked",false)){
                        // p.attr("checked")
                        // p.click();
                    }
                }else if(true == $(this).attr("checked")){
                }
            });
        //节点折叠
        $(".J-switch").live("click",function(){
                if($(this).hasClass("close")){
                    var id = $(this).parent().parent().parent().attr("id");
                    $(this).removeClass("close").addClass("open");
                    //判断是否已经加载了子节点，如果加载，则只需要控制隐藏和现实，而不发送ajax请求
                    var flag = $("#"+id).find(".nameList").length ==0 && $("#"+id).find(".level").length ==0;
                    if(flag){
                        var url = treeAction.settings.urlNode;
                        $.post(url,{id:id},function(data){
                                var data = eval('(' + data + ')');
                                if(data.success && data.showData[0].id == id){
                                    var treeData = data.showData;
                                    treeAction.createValue(treeData[0]);
                                    var son = treeAction.findson(id,treeData);
                                    if(son.length != 0){
                                        treeAction.createSon(id,son);
                                    }
                                }
                            });
                    }
                    else{
                        $(this).parent().parent().siblings(".level").show();
                        $(this).parent().siblings(".nameList").show();
                    }
                }else if($(this).hasClass("open")){
                    $(this).removeClass("open").addClass("close");
                    $(this).parent().parent().parent().find(".level").hide();
                    $(this).parent().parent().parent().find(".nameList").hide();
                    var sonNode = $(this).parent().parent().parent().find(".J-switch");
                    $(sonNode).each(function(){
                            treeAction.nodeSwitch(this);
                        });
                }
            });
        $(".J-submit").click(function(){
                var checkNode = $(".treeCont").find(".J-checkValue");
                var checkArray = [];
                $(checkNode).each(function(){
                        if(this.attr("checked")){
                            var value = this.attr("name");
                            checkArray.push(value);
                        }
                    })
            });
    },
    nodeSwitch:function(node){
        if($(node).hasClass("open")){
            $(node).removeClass("open").addClass("close");
        }
    },
    showErrorMsg:function(status){
        var showMsg = "";
        var appendNode = treeAction.settings.appendNode;
        switch (status)
        {
        case 0:showMsg="您还没有可添加的人员";
            break;
        case 1:showMsg="加载信息失败，请重试";
            break;
        default: break;
        }
        var errorHtml = "<div class=\"treeCont\"><p class=\"treeError\">"+showMsg+"</p><span class=\"treeClose J-treeClose\"></span></div>";
        $("."+appendNode).append(errorHtml);
    },
    /*
     *创建第一层
     */
    createFirstLevel:function(treeData){
        var array = treeAction.findlevel(0,treeData);
        var len = array.length;
        var treeDataLen = treeData.length;
        var parentId = treeData[0].parentId;
        var html = [];
        html.push("<div class=\"treeCont\"><span class=\"treeClose J-treeClose\"></span><p class=\"tree-title\"><input type =\"checkbox\" name=\""+treeData[0].currGroupName+"\" class=\"J-checkAll\" /><span class=\"title\">全选</span></p><ul class=\"tree-main\">");
        var list = "";
        for(var i =0;i<len;i++){
            //var currId = array[i].id;
            alert(array[i].pid);
            list += "<li class=\"level-0\" id="+array[i].id+"><div class=\"tree-list-cont\"><p class=\"lft\"><span class=\"switchIcon J-switch level-0\"></span><input type =\"checkbox\" name=\"" + array[i].name + "\" pid=\"" + array[i].pid + "\" class=\"J-check J-checkValue\" /><span class=\"title\">"+array[i].name+"</span></p></div></li>";
        }
        list+="</ul><div class=\"tree-footer\"><p class=\"tree-operate\"><button type=\"submit\" class=\"J-submit\">确定</button><span class=\"J-treeClose\">取消</span></p></div></div>";
        html.push(list);
        $("body").append(html.join(""));
        treeAction.addNodeIcon(treeData);
        treeAction.getCurrUserParent(treeData);
        for ( var j = 0 ; j< parentId.length ; j++ ){
            $("#"+parentId[j]).children().children().children(".J-switch").removeClass("close").addClass("open");
        }
    },
    addNodeIcon:function(treeData){
        $(treeData).each(function(){
                if(true == this.hasChild){
                    $("#"+this.id).children().children().children(".J-switch").addClass("close");
                }
            })
    },
    /**
     *获得当前用户的最上层父节点(即第一层父节点)
     */
    getCurrUserParent:function(treeData){
        var parentId = treeData[0].parentId;
        var len = parentId.length;
        for( var i = 0 ; i < len ; i++ ){
            for( var j = 1; j < treeData.length ; j++ ){
                if( treeData[j].id == parentId[i] ){
                    treeAction.createCurrLevel(treeData[j],treeData);
                }
            }
        }
    },
    /*
     *创建至当前用户层级
     */
    createCurrLevel:function(parent,treeData){
        var list = "";
        treeAction.createValue(parent);
        var id = parent.id;
        var son = treeAction.findson(parent.id,treeData);
        if(son.length != 0){
            treeAction.createSon(id,son);
            for(var j = 0 ; j < son.length ; j++ ){
                treeAction.createCurrLevel(son[j],treeData);
            }
        }
    },
    /*
     *创建当前节点的姓名
     */
    createValue:function(parent){
        var list = "";
        var id = parent.id;
        if(parent.value){
            var valueArray = parent.value;
            var valueLen = valueArray.length;
            list+="<ul class=\"nameList\">";
            for(var j = 0;j<valueLen;j++){
                list +="<li><input type =\"checkbox\" name=\"" + valueArray[j] + "\" class=\"J-check J-checkName\"/><span class=\"title\">"+valueArray[j]+"</span></li>";
            }
            list+= "</ul>";
            $("#"+id).children().children().children(".J-switch").addClass("open");
        }
        $("#"+parent.id).children(".tree-list-cont").append(list);
        if ( true === $("#" + parent.id).children(".tree-list-cont").find(".J-checkValue").eq(0).attr("checked") ){
            $("#" + parent.id).children(".tree-list-cont").find(".J-check").attr("checked",true);
        } else if ( false === $("#" + parent.id).children(".tree-list-cont").find(".J-checkValue").eq(0).attr("checked") ){
            $("#" + parent.id).children(".tree-list-cont").find(".J-check").attr("checked",false);
        }
    },
    /*
     *
     */
    createSon:function(id,son){
        var sonList = "<ul class=\"level\">";
        for(var i = 0;i<son.length;i++){
            sonList += "<li id="+son[i].id+" class=level-"+son[i].level+"><div class=\"tree-list-cont\"><p class=\"lft\"><span class=\"switchIcon J-switch level-"+son[i].level+"\"></span><input type =\"checkbox\" name=\"" + son[i].name + "\" class=\"J-check J-checkValue\" pid=\"" + son[i].pid + "\" /><span class=\"title\">"+son[i].name+"</span></p></li>";
        }
        sonList+="</ul>";
        $("#"+id).append(sonList);
        treeAction.addNodeIcon(son);
        if ( true === $("#" + id).children(".tree-list-cont").find(".J-checkValue").eq(0).attr("checked") ){
            $("#" + id).children(".level").find(".J-check").attr("checked",true);
        } else if ( false === $("#" + id).children(".tree-list-cont").find(".J-checkValue").eq(0).attr("checked") ){
            $("#" + id).children(".level").find(".J-check").attr("checked",false);
        }
    },
    /*
     *判断是否存在value或者子节点
     */
    hasChild:function(elem){
        if(elem.hasChild == true)
            return true;
        else
            return false;
    },
    /*
     * 创建子层
     */
    createSonLevel:function(currId){
        var son= treeAction.findson(currId);
        var sonHtml = "";
        if(son.length != 0){
            sonHtml += "<ul class=\"level\">";

            for(var i =0;i<son.length;i++){
                sonHtml += "<li id="+son[i].id+" class=level-"+son[i].level+"><div class=\"tree-list-cont\"><p class=\"lft\"><span class=\"switchIcon J-switch level-"+son[i].level+"\"></span><input type =\"checkbox\" name=\"" + son[i].name + "\" class=\"J-check J-checkValue\" pid=\"" + son[i].pid + "\" /><span class=\"title\">"+son[i].name+"</span></p>";
                if(son[i].value.length != 0){
                    var valueArray = son[i].value;
                    var valueLen = valueArray.length;
                    //$(".J-switch").addClass("close");
                    sonHtml+="<ul class=\"nameList\">";
                    for(var j = 0;j<valueLen;j++){
                        sonHtml +="<li><input type =\"checkbox\" name=\"" + valueArray[j] + "\" class=\"J-check J-checkName\"/><span class=\"title\">"+valueArray[j]+"</span></li>";
                    }
                    sonHtml+= "</ul>";
                }
                sonHtml += "</div>";
                var sonEnd = treeAction.findson(son[i].id);
                var sonEndLen = sonEnd.length;
                if(sonEndLen!= 0){
                    // sonHtml += createSonLevel.apply(treeAction,son[i].id);
                    sonHtml+=treeAction.createSonLevel(son[i].id)
                }
                sonHtml += "</li>";
            }
            sonHtml += "</ul>";
        }
        return sonHtml;
    },
    /**
     *获取当前层级下的节点
     *param[currlevel] 传入当前层级
     */
    findlevel:function(level,treeData){
        var currarray = [];
        $(treeData).each(function(){
                if(level == this.level){
                    currarray.push(this);
                }
            });
        return currarray;
    },
    /**
     *获取当前层级的子节点
     *param[currid] 传入当前节点id
     */
    findson:function(currid,treeData){
        var sonarray = [];
        $(treeData).each(function(){
                if(currid == this.pid){
                    sonarray.push(this);
                }
            })
        return sonarray;
    }
}
